<template>
  <div id="export">
    <Button type="primary" :disabled="isDownloading" :loading="isDownloading" @click="selectExtendAttr">{{
      btnText
    }}</Button>
  </div>
</template>

<script>
import selectExtendAttribute from './select-extend-attribute.vue'

export default {
  name: 'export',
  props: {
    btnText: {
      type: String,
      default: '导出'
    },
    requestMethod: {
      type: String,
      default: 'get'
    },
    requestPath: {
      type: String,
      default: '',
      required: true
    },
    requestParams: {
      type: Object,
      default: () => ({})
    },
    queryTemplateParams: {
      type: Object,
      default: () => ({})
    },
    exportType: {
      type: String,
      default: 'exportData',
      validator: function(value) {
        return ['exportData', 'downloadTemplate'].includes(value)
      }
    }
  },
  data() {
    return {
      isDownloading: false
    }
  },
  methods: {
    selectExtendAttr() {
      const {
        exportType,
        queryTemplateParams: { requestPath, requestMethod, requestParams }
      } = this
      if (exportType === 'downloadTemplate') {
        new this.$pageModal(
          selectExtendAttribute,
          {
            props: {
              requestPath,
              requestMethod,
              requestParams
            }
          },
          data => {
            if (data) {
              console.log('选择的拓展属性模板：', data)
              this.handleExport(data)
            }
          }
        )
      } else {
        this.handleExport()
      }
    },
    handleExport(extraRequestParams = {}) {
      const { requestMethod, requestPath, requestParams } = this
      const reqMethod = requestMethod.toLowerCase()
      this.isDownloading = true
      $http[reqMethod](requestPath, Object.assign({}, requestParams, extraRequestParams), null, {
        responseType: 'blob'
      })
        .then(res => {
          if (res.status === 200) {
            const { headers } = res
            const blob = res.data
            const fileName = decodeURIComponent(headers['content-disposition'].split(';')[1].split('filename=')[1])
            const a = document.createElement('a')
            a.href = URL.createObjectURL(blob)
            a.download = fileName
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
          }
        })
        .catch(err => console.error(err))
        .finally(() => (this.isDownloading = false))
    }
  }
}
</script>

<style id="export">
#export {
  display: flex;
  align-items: center;
}
</style>
